<template>
  <div class="system-status-container">
    <div class="header">
      <h2>系统状态监控</h2>
      <div class="header-actions">
        <p>实时监控系统运行状态和性能指标</p>
        <div class="settings">
          <el-button size="small" @click="refreshAllData" type="primary">立即刷新</el-button>
          <el-button size="small" @click="showSettingsDialog">设置刷新频率</el-button>
        </div>
      </div>
    </div>

    <!-- 系统概览 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon cpu-icon">
              <el-icon><cpu /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-title">CPU使用率</div>
              <div class="overview-value">{{ systemInfo.cpuUsage.toFixed(2) }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon memory-icon">
              <el-icon><coin /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-title">内存使用率</div>
              <div class="overview-value">{{ systemInfo.memoryUsage.toFixed(2) }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon disk-icon">
              <el-icon><monitor /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-title">磁盘使用率</div>
              <div class="overview-value">{{ systemInfo.diskUsage }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon date-icon">
              <el-icon><calendar /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-title">当前日期</div>
              <div class="overview-value">{{ systemInfo.currentDate }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统信息 -->
    <el-row :gutter="20" class="info-row">
      <el-col :span="12">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>系统信息</span>
            </div>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="操作系统">{{ systemInfo.osName }}</el-descriptions-item>
            <el-descriptions-item label="系统架构">{{ systemInfo.architecture }}</el-descriptions-item>
            <el-descriptions-item label="Java版本">{{ systemInfo.javaVersion }}</el-descriptions-item>
            <el-descriptions-item label="运行时间">{{ formatUptime(systemInfo.uptime) }}</el-descriptions-item>
            <el-descriptions-item label="启动时间">{{ formatDate(systemInfo.startTime) }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>应用信息</span>
            </div>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="应用名称">{{ appInfo.name }}</el-descriptions-item>
            <el-descriptions-item label="应用版本">{{ appInfo.version }}</el-descriptions-item>
            <el-descriptions-item label="端口">{{ appInfo.port }}</el-descriptions-item>
            <el-descriptions-item label="环境">{{ appInfo.environment }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag type="success">运行中</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>

    <!-- 性能图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>CPU使用率趋势</span>
              <div>
                <el-button size="small" @click="refreshAllData">刷新</el-button>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="generateCpuTrendChartOption(chartData.cpuTrend24h, 'CPU使用率趋势 - 最近24小时')" autoresize />
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>内存使用情况</span>
              <div>
                <el-button size="small" @click="refreshAllData">刷新</el-button>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="generateMemoryTrendChartOption(chartData.memoryTrend24h, '内存使用情况 - 最近24小时')" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 7天趋势图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>CPU使用率趋势 - 最近7天</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="generateCpuTrendChartOption(chartData.cpuTrend7d, 'CPU使用率趋势 - 最近7天')" autoresize />
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>内存使用情况 - 最近7天</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="generateMemoryTrendChartOption(chartData.memoryTrend7d, '内存使用情况 - 最近7天')" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- API监控 -->
    <el-card class="api-monitor-card">
      <template #header>
        <div class="card-header">
          <span>API监控</span>
          <div>
            <el-dropdown @command="handleResetCommand">
              <el-button size="small">
                重置数据<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="resetAll">全部重置</el-dropdown-item>
                  <el-dropdown-item command="reset1Hour">1小时后重置</el-dropdown-item>
                  <el-dropdown-item command="reset6Hours">6小时后重置</el-dropdown-item>
                  <el-dropdown-item command="reset24Hours">24小时后重置</el-dropdown-item>
                  <el-dropdown-item command="reset7Days">7天后重置</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="api-stat">
            <div class="api-stat-label">总请求数</div>
            <div class="api-stat-value">{{ apiMonitor.totalRequests }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="api-stat">
            <div class="api-stat-label">错误请求数</div>
            <div class="api-stat-value error">{{ apiMonitor.errorRequests }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="api-stat">
            <div class="api-stat-label">平均响应时间(ms)</div>
            <div class="api-stat-value">{{ apiMonitor.avgResponseTime }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="api-stat">
            <div class="api-stat-label">成功率</div>
            <div class="api-stat-value" :class="{ error: apiMonitor.errorRequests / apiMonitor.totalRequests > 0.05 }">
              {{ apiMonitor.totalRequests > 0 ? ((1 - apiMonitor.errorRequests / apiMonitor.totalRequests) * 100).toFixed(2) + '%' : '0%' }}
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- Top API端点 -->
      <div class="api-endpoints">
        <h4>Top API端点 (按请求数)</h4>
        <el-table :data="apiMonitor.topEndpoints" style="width: 100%" size="small">
          <el-table-column prop="url" label="API端点" show-overflow-tooltip />
          <el-table-column prop="method" label="方法" width="80" />
          <el-table-column prop="requestCount" label="请求数" width="100" />
          <el-table-column prop="errorCount" label="错误数" width="80" />
          <el-table-column prop="avgResponseTime" label="平均响应时间(ms)" width="120" />
          <el-table-column prop="successRate" label="成功率(%)" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.successRate > 95 ? 'success' : scope.row.successRate > 90 ? 'warning' : 'danger'">
                {{ scope.row.successRate }}%
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>


    <!-- 设置对话框 -->
    <el-dialog v-model="settingsDialogVisible" title="刷新设置" width="400px">
      <el-form label-width="100px">
        <el-form-item label="刷新频率">
          <el-select v-model="refreshSettings.interval" placeholder="请选择刷新频率">
            <el-option label="1分钟" :value="60000"></el-option>
            <el-option label="30分钟" :value="1800000"></el-option>
            <el-option label="1小时" :value="3600000"></el-option>
            <el-option label="12小时" :value="43200000"></el-option>
            <el-option label="24小时" :value="86400000"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="自动刷新">
          <el-switch v-model="refreshSettings.enabled"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="resetSettings">重置</el-button>
      <el-button type="primary" @click="saveSettings">保存</el-button>
    </span>
      </template>
    </el-dialog>
  </div>

</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Cpu, Coin, Monitor, Connection, Calendar } from '@element-plus/icons-vue'
import { systemStatusApi } from '../../utils/systemStatusApi'
import VChart from 'vue-echarts'
import * as echarts from 'echarts'

// 响应式数据
const systemInfo = ref({
  cpuUsage: 0,
  memoryUsage: 0,
  diskUsage: 0,
  currentDate: '',
  osName: '',
  architecture: '',
  javaVersion: '',
  uptime: 0,
  startTime: '',
  serverTime: ''
})

const appInfo = ref({
  name: '',
  version: '',
  port: 0,
  environment: '',
  status: ''
})

// API监控数据
const apiMonitor = ref({
  totalRequests: 0,
  errorRequests: 0,
  avgResponseTime: 0,
  endpoints: [] as any[],
  topEndpoints: [] as any[] // 添加Top API端点数据
})

// 图表数据
const chartData = ref({
  cpuTrend24h: [] as any[],
  cpuTrend7d: [] as any[],
  memoryTrend24h: [] as any[],
  memoryTrend7d: [] as any[]
})

// 图表配置
const chartOptions = ref({
  cpu24h: {},
  cpu7d: {},
  memory24h: {},
  memory7d: {}
})

// 加载历史数据标志
const loadingHistory = ref(false)


// 刷新设置
const refreshSettings = ref({
  interval: 3600000, // 默认1小时
  enabled: true
})

// 设置对话框
const settingsDialogVisible = ref(false)

// 定时器
let refreshTimer: any = null

// 获取CPU颜色
const getCpuColor = (usage: number) => {
  if (usage < 50) return '#5cb87a'
  if (usage < 80) return '#e6a23c'
  return '#f56c6c'
}

// 获取内存颜色
const getMemoryColor = (usage: number) => {
  if (usage < 60) return '#5cb87a'
  if (usage < 85) return '#e6a23c'
  return '#f56c6c'
}

// 获取活动类型标签
const getActivityTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    'INFO': 'info',
    'WARN': 'warning',
    'ERROR': 'danger',
    'SUCCESS': 'success'
  }
  return tagMap[type] || 'info'
}

// 获取活动类型名称
const getActivityTypeName = (type: string) => {
  const nameMap: Record<string, string> = {
    'INFO': '信息',
    'WARN': '警告',
    'ERROR': '错误',
    'SUCCESS': '成功'
  }
  return nameMap[type] || type
}

// 格式化日期时间
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 格式化运行时间
const formatUptime = (seconds: number) => {
  if (!seconds) return '0秒'

  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  let result = ''
  if (days > 0) result += `${days}天 `
  if (hours > 0) result += `${hours}小时 `
  if (minutes > 0) result += `${minutes}分钟 `
  result += `${secs}秒`

  return result.trim()
}

// 生成CPU使用率趋势图表配置
const generateCpuTrendChartOption = (data: any[], title: string) => {
  const is24h = title.includes('24小时');
  return {
    title: {
      text: title,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const param = params[0];
        const date = new Date(param.name);
        const formattedTime = is24h ? date.toLocaleString('zh-CN', { hour: '2-digit', minute: '2-digit' }) : date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit' });
        return `${formattedTime}<br/>${param.seriesName}: ${param.value}%`;
      }
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.time),
      axisLabel: {
        rotate: is24h ? 45 : 0,
        fontSize: 12,
        formatter: (value: string) => {
          const date = new Date(value);
          return is24h ? date.toLocaleString('zh-CN', { hour: '2-digit', minute: '2-digit' }) : date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit' });
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '使用率(%)',
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [{
      name: 'CPU使用率',
      data: data.map(item => item.value),
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      },
      lineStyle: {
        width: 2
      }
    }]
  }
}

// 生成内存使用情况图表配置
const generateMemoryTrendChartOption = (data: any[], title: string) => {
  const is24h = title.includes('24小时');
  return {
    title: {
      text: title,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const param = params[0];
        const date = new Date(param.name);
        const formattedTime = is24h ? date.toLocaleString('zh-CN', { hour: '2-digit', minute: '2-digit' }) : date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit' });
        return `${formattedTime}<br/>${param.seriesName}: ${param.value}%`;
      }
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.time),
      axisLabel: {
        rotate: is24h ? 45 : 0,
        fontSize: 12,
        formatter: (value: string) => {
          const date = new Date(value);
          return is24h ? date.toLocaleString('zh-CN', { hour: '2-digit', minute: '2-digit' }) : date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit' });
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '使用率(%)',
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [{
      name: '内存使用率',
      data: data.map(item => item.value),
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      },
      lineStyle: {
        width: 2
      }
    }]
  }
}

// 获取CPU历史数据
const fetchCpuHistory = async (period: string) => {
  try {
    const response = await systemStatusApi.getCpuHistory(period)
    const data = response.data

    // 转换数据格式
    const formattedData = data.map((item: any) => ({
      time: item.timestamp ? new Date(item.timestamp).toISOString() : '', // 改为 ISO 格式
      value: item.value || 0
    }))
    // console.log(`CPU History Data (${period}):`, formattedData) // 添加日志
    return formattedData
  } catch (error: any) {
    console.error(`获取CPU历史数据(${period})失败:`, error)
    ElMessage.error(`获取CPU历史数据(${period})失败: ` + (error.response?.data?.message || error.message))
    return []
  }
}

// 获取内存历史数据
const fetchMemoryHistory = async (period: string) => {
  try {
    const response = await systemStatusApi.getMemoryHistory(period)
    const data = response.data

    // 转换数据格式
    const formattedData = data.map((item: any) => ({
      time: item.timestamp ? new Date(item.timestamp).toISOString() : '', // 改为 ISO 格式
      value: item.value || 0
    }))
    // console.log(`Memory History Data (${period}):`, formattedData) // 添加日志
    return formattedData
  } catch (error: any) {
    console.error(`获取内存历史数据(${period})失败:`, error)
    ElMessage.error(`获取内存历史数据(${period})失败: ` + (error.response?.data?.message || error.message))
    return []
  }
}

// 加载所有历史数据
const loadHistoryData = async () => {
  loadingHistory.value = true
  try {
    // 并行加载所有历史数据
    const [cpu24h, cpu7d, memory24h, memory7d] = await Promise.all([
      fetchCpuHistory('24h'),
      fetchCpuHistory('7d'),
      fetchMemoryHistory('24h'),
      fetchMemoryHistory('7d')
    ])

    // 更新图表数据
    chartData.value = {
      cpuTrend24h: cpu24h,
      cpuTrend7d: cpu7d,
      memoryTrend24h: memory24h,
      memoryTrend7d: memory7d
    }
  } catch (error) {
    console.error('加载历史数据失败:', error)
    ElMessage.error('加载历史数据失败')
  } finally {
    loadingHistory.value = false
  }
}

// 获取服务器状态
const fetchServerStatus = async () => {
  try {
    const response = await systemStatusApi.getServerStatus()
    const data = response.data

    systemInfo.value = {
      cpuUsage: data.cpuUsage || 0,
      memoryUsage: data.memoryUsage || 0,
      diskUsage: data.diskUsage || 0,
      currentDate: data.currentDate || '',
      osName: data.osName || '',
      architecture: data.architecture || '',
      javaVersion: data.javaVersion || '',
      uptime: data.uptime || 0,
      startTime: data.startTime || '',
      serverTime: data.serverTime || ''
    }
    // console.log('Server Status Data:', data)

    appInfo.value = {
      name: data.appName || '',
      version: data.appVersion || '',
      port: data.appPort || 0,
      environment: data.environment || '',
      status: data.status || ''
    }
  } catch (error: any) {
    console.error('获取服务器状态失败:', error)
    ElMessage.error('获取服务器状态失败: ' + (error.response?.data?.message || error.message))
  }
}

// 获取API监控信息
const fetchApiMonitor = async () => {
  try {
    const response = await systemStatusApi.getApiMonitor()
    const data = response.data

    apiMonitor.value = {
      totalRequests: data.totalRequests || 0,
      errorRequests: data.errorRequests || 0,
      avgResponseTime: data.avgResponseTime || 0,
      endpoints: data.endpoints || [],
      topEndpoints: data.topEndpoints || []
    }
    // console.log('API Monitor Data:', data)
  } catch (error: any) {
    console.error('获取API监控信息失败:', error)
    ElMessage.error('获取API监控信息失败: ' + (error.response?.data?.message || error.message))
  }
}


// 刷新所有数据
const refreshAllData = async () => {
  try {
    await Promise.all([
      fetchServerStatus(),
      fetchApiMonitor()
    ])
    // 同时加载历史数据
    await loadHistoryData()
    ElMessage.success('数据已刷新')
  } catch (error) {
    ElMessage.error('刷新数据失败')
  }
}

// 定时刷新数据
const startAutoRefresh = () => {
  if (refreshSettings.value.enabled) {
    refreshTimer = setInterval(() => {
      refreshAllData()
    }, refreshSettings.value.interval)
  }
}

// 停止定时刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  refreshAllData()
  startAutoRefresh()
})

// 显示设置对话框
const showSettingsDialog = () => {
  settingsDialogVisible.value = true
}

// 保存设置
const saveSettings = () => {
  stopAutoRefresh()
  if (refreshSettings.value.enabled) {
    startAutoRefresh()
  }
  settingsDialogVisible.value = false
  ElMessage.success('设置已保存')
}

// 处理重置命令
const handleResetCommand = async (command: string) => {
  try {
    let hours: number | undefined = undefined

    switch (command) {
      case 'resetAll':
        hours = undefined
        break
      case 'reset1Hour':
        hours = 1
        break
      case 'reset6Hours':
        hours = 6
        break
      case 'reset24Hours':
        hours = 24
        break
      case 'reset7Days':
        hours = 168 // 7天 = 168小时
        break
      default:
        hours = undefined
    }

    await systemStatusApi.resetApiMonitorData(hours)

    // 刷新API监控数据
    await fetchApiMonitor()

    ElMessage.success('API监控数据已重置')
  } catch (error: any) {
    console.error('重置API监控数据失败:', error)
    ElMessage.error('重置API监控数据失败: ' + (error.response?.data?.message || error.message))
  }
}

// 重置设置
const resetSettings = () => {
  refreshSettings.value.interval = 3600000
  refreshSettings.value.enabled = true
  stopAutoRefresh()
  startAutoRefresh()
  ElMessage.success('设置已重置')
}

// 组件卸载时清理定时器
onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style scoped>
.system-status-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.header p {
  color: #606266;
  margin: 0;
}

.overview-row {
  margin-bottom: 20px;
}

.overview-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.overview-item {
  display: flex;
  align-items: center;
}

.overview-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.cpu-icon {
  background-color: #409eff;
}

.memory-icon {
  background-color: #67c23a;
}

.disk-icon {
  background-color: #e6a23c;
}

.network-icon {
  background-color: #f56c6c;
}

.date-icon {
  background-color: #409eff;
}

.overview-info {
  flex: 1;
}

.overview-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.overview-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.info-row {
  margin-bottom: 20px;
}

.info-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header div {
  display: flex;
  align-items: center;
  gap: 10px;
}

.chart-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.activity-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.api-monitor-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.api-stat {
  text-align: center;
  padding: 20px 0;
}

.api-stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.api-stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.api-stat-value.error {
  color: #f56c6c;
}

.api-endpoints {
  margin-top: 20px;
}

.api-endpoints h4 {
  margin: 15px 0 10px 0;
  color: #303133;
}


.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.settings {
  margin-left: 20px;
}
</style>
